package com.changgou.weixinPay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.weixinPay.service.WeixinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import entity.Result;
import entity.StatusCode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/weixin/pay")
@CrossOrigin
public class WeixinPayController {

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /***
     * 创建二维码
     * 普通订单附加信息：
     *      exchange：exchange.order
     *      routingkey: queue.order
     * 秒杀订单附加信息：
     *      exchange：exchange.seckillorder
     *      routingkey: queue.seckillorder
     *exchange+routingKey->JSON->attach打包发送到微信服务器
     * @return
     */
    @RequestMapping(value = "/create/native")
    public Result createNative(@RequestParam Map<String,String> parameter){
        Map<String,String> resultMap = weixinPayService.createNative(parameter);
        return new Result(true, StatusCode.OK,"创建二维码预付订单成功！",resultMap);
    }

    /***
     * 查询支付状态
     * @param outtradeno
     * @return
     */
    @GetMapping(value = "/status/query")
    public Result queryStatus(String outtradeno){
        Map<String,String> resultMap = weixinPayService.queryPayStatus(outtradeno);
        return new Result(true,StatusCode.OK,"查询状态成功！",resultMap);
    }


    /***
     * 支付回调
     * @param request
     * @return
     */
    @RequestMapping(value = "/notify/url")
    public String notifyUrl(HttpServletRequest request){
        InputStream inStream;
        try {
            //读取支付回调数据
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            /*// 将支付回调数据转换成xml字符串
            String result = new String(outSteam.toByteArray(), "utf-8");
            //将xml字符串转换成Map结构
            Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
            //需要传到mq的数据
            Map<String,String> mqMap = new HashMap<>();
            mqMap.put("return_code",resultMap.get("return_code"));
            mqMap.put("result_code",resultMap.get("result_code"));
            mqMap.put("out_trade_no",resultMap.get("out_trade_no"));
            mqMap.put("time_end",resultMap.get("time_end"));
            mqMap.put("transaction_id",resultMap.get("transaction_id"));
            //获取自定义数据
            String attach = resultMap.get("attach");
            //转为Map
            Map<String,String> attachMap = JSON.parseObject(attach, Map.class);
*/

            //以下数据仅供测试
            Map<String, String> map = new HashMap<>();
            map.put("return_code","SUCCESS");
            map.put("result_code","FAIL");
            map.put("out_trade_no","1314516092194000896");
            map.put("transaction_id","123");
            map.put("time_end",new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            Map<String,String> attach = new HashMap<>();
            attach.put("exchange","seckillOrder");
            attach.put("routingkey","seckillkey");
            attach.put("username","szitheima");
            //转换为JSON字符串
            map.put("attach",JSON.toJSONString(attach));


            //将响应数据发送到MQ队列
//            rabbitTemplate.convertAndSend("exchange.order","queue.order", JSON.toJSONString(map));
//            rabbitTemplate.convertAndSend(attachMap.get("exchange"),attachMap.get("routingkey"), JSON.toJSONString(mqMap));
            rabbitTemplate.convertAndSend("exchange.seckillorder","queue.seckillorder", JSON.toJSONString(map));

            //响应数据设置
            Map respMap = new HashMap();
            respMap.put("return_code","SUCCESS");
            respMap.put("return_msg","OK");
            return WXPayUtil.mapToXml(respMap);
        } catch (Exception e) {
            e.printStackTrace();
            //记录错误日志
        }
        return null;
    }


}
